<?php

namespace app\apiadmin\service\invitation;

use app\apiadmin\command\getToken;
use app\apiadmin\controller\liveManager\LiveStatus;
use app\apiadmin\controller\user\User;
use app\apiadmin\model\invitation\InvitationModel;
use app\apiadmin\service\liveManager\LiveManagerService;
use app\common\utils\Res;
use DateInterval;
use DatePeriod;
use DateTime;
use think\facade\Db;

class InvitationService
{

    /**
     * @author: zwx
     * @Description: 根据条件查询数据列表
     * @param {*} $param
     * @Date: 2024-05-12 14:50:39
     */
    public static function getUserInfo($param, $uid)
    {

        $limit = !isset($param['pageSize']) ? 10 : (int) $param['pageSize'];
        $offset = ($param['pageNumber'] - 1) * $limit;

        //登录信息
        $sender = db::name('siyu_sys_member')->where('uid', $uid)->find();

        $map = [];
        $map["y.del"] = 0;

        $map["y.liveId"] = $param["liveId"];
        $map["y.sender"] = $sender['user_name'];

        if (isset($param["wx_name"]) && !empty($param["wx_name"])) {
            $map[] = ["y.nickname", 'like', '%' . $param["wx_name"] . '%'];
        }
        if (isset($param["invitation_status"]) && !empty($param["invitation_status"])) {
            $map["y.invitation_status"] = $param["invitation_status"];
        }
        if (isset($param["signin_status"]) && !empty($param["signin_status"])) {
            $map["y.signin_status"] = $param["signin_status"];
        }

        if (isset($param["planid"]) && !empty($param["planid"])) {
            $map["y.planid"] = $param["planid"];
        }

        $findName = "y.*";

        //直播信息
        $livemanager = db::name('siyu_live_manager')->where(array('id' => $param['liveId'], 'del' => 0))->find();

        //邀约计划
        $planlist = db::table('xh_siyu_invitation_plan')->alias('y')
            ->join('xh_siyu_invitation_msg m', 'y.id = m.planid and y.liveId = m.liveId', 'left')
            ->join('xh_siyu_sys_member t', 't.user_name = y.sender', 'left')
            ->field('y.*,m.desc,m.id as msgid,t.nick_name')
            ->where(array('y.liveId' => $param['liveId'], 'y.del' => 0))->select()->toArray();

        if ((!isset($param["planid"]) || empty($param["planid"])) && $planlist) {
            $map["y.planid"] = $planlist[0]['id'];
        }

        $cha = 0;
        foreach ($planlist as $k => $v) {
            $cha += $v['count'] - $v['count_hav'];
        }

        //查询分页数据和条数
        $result = InvitationModel::pageMap($map, $findName, $offset, $limit);
        $total = InvitationModel::pageMapCount($map);

        // //按照日期排列每天人数

        $invitationusers = Db::table('xh_siyu_invitation_user')->where(['liveId' => $param['liveId'], 'del' => 0])->select()->toArray();
        $unoins = array_column($invitationusers, 'wx_unionid');

        $data = Db::table('xh_qwuser_1')->where(['wx_unionid' => $unoins])->field('addtime,wx_unionid')->group('wx_unionid')->order('addtime desc')->select()->toArray();

        $data1 = [];
        foreach ($data as $k => $v) {
            if ($v['addtime']) {
                $data1[date('Y-m-d', strtotime($v['addtime']))][] = $v;
            } else {
                $data1['2024-01-01'][] = $v;
            }

        }

        $usernumbydate = [];
        foreach ($data1 as $k => $v) {
            $a = [];
            $a['date'] = $k;
            $a['num'] = count($v);
            $usernumbydate[] = $a;
        }

        $data = [
            'list' => $result,
            'total' => $total,
            'sender' => $sender,
            'livemanager' => $livemanager,
            'planlist' => $planlist,
            'renshu' => count($data),
            'renshu_hav' => count($data) - $cha,
            'usernumbydate' => $usernumbydate,
            'usernumbydate_num' => count($data),
        ];
        return Res::ok($data);
    }

    /**
     * @author: zwx
     * @Description: 查询标签
     * @param {*} $param
     * @Date: 2024-06-27 18:08:11
     */
    public static function querybiaoqian($param)
    {

        //查询标签
        $map = [];
        $map["t.del"] = 0;

        if (isset($param["title"]) && !empty($param["title"])) {
            $map[] = ["t.name", 'like', '%' . $param["title"] . '%'];
        }

        $findName = "t.*";

        $tags = InvitationModel::querybiaoqian($map, $findName);

        //查询标签组
        $map2 = [];
        $map2["g.del"] = 0;

        $findName2 = "g.*";
        $taggroups = InvitationModel::querybiaoqiangroup($map2, $findName2);

        //组合数据
        $data = [];
        foreach ($tags as $k => $v) {
            $v['click'] = 0;
            $data[$v['groupid']]['tags'][$v['tagid']] = $v;
        }

        foreach ($data as $k => $v) {
            foreach ($taggroups as $k2 => $v2) {
                if ($v2['groupid'] == $k) {
                    $data[$k]['groups'] = $v2;
                }
            }
        }

        return Res::ok($data);

    }

    /**
     * @author: zwx
     * @Description: 查询群发内容
     * @param {*} $param
     * @Date: 2024-06-27 18:08:11
     */
    public static function querycontent($param)
    {

        $msg = db::table('xh_siyu_invitation_msg')->where(array('liveId' => $param["liveId"]))->find();
        if (!$msg) {
            $msg = '';
        }
        return Res::ok($msg);

    }

    /**
     * @author: zwx
     * @Description: 查询用户信息
     * @param {*} $param
     * @Date: 2024-06-28 00:11:50
     */
    public static function querytagUser($param)
    {

        //查询标签
        $map = [];
        $map1 = [];
        $map["u.del"] = 0;
        $map[] = ["q.wx_unionid", '<>', ''];
        //权限管控
        $map = self::getAccountInfo($map, "u.zhujiao", $param["sender"]);

//        $users1 = [];
        //        $users2 = [];
        //
        //        $findName = "u.userid,u.zhujiao,q.wx_unionid,q.wx_name,q.wx_avatar,q.phone";
        //        if (isset($param['tags1']) && !empty($param['tags1'])) {
        //            $map1[] = ["u.tagid", 'in', $param['tags1']];
        //            $users1 = InvitationModel::querytagUser($map1, $findName);
        //        }
        //        if (isset($param['tags']) && !empty($param['tags'])) {
        //            $map[] = ["u.tagid", 'in', $param['tags']];
        //            $users2 = InvitationModel::querytagUser($map, $findName);
        //        }
        //        if(!empty($users1) && !empty($users2)  ){
        //            foreach($users1 as $k =>&$v){
        //                foreach($users2 as $kk=>&$vv){
        //                    if($v['userid'] == $vv['userid']){
        //                        unset($users1[$k]);
        //                        continue;
        //                    }
        //                }
        //            }
        //            $users = $users1;
        //        }else if(empty($users1) && !empty($users2)  ){
        //            $map[] = ["u.tagid", 'not in', $param['tags']];
        //            $users2 = InvitationModel::querytagUser($map, $findName);
        //            $users = $users2;
        //        } else if (!empty($users1) && empty($users2)) {
        //            $users = $users1;
        //        } else if (empty($users1) && empty($users2)) {
        //            $users = $users1;
        //        }

        if (isset($param["tags"]) && !empty($param["tags"])) {
            $map[] = ["u.tagid", 'in', $param['tags']];
        }

        $findName = "u.userid,u.zhujiao,q.wx_unionid,q.wx_name,q.wx_avatar,q.phone";

        if (isset($param["startdate"]) && !empty($param["startdate"]) && isset($param["enddate"]) && !empty($param["enddate"])) {
            $map[] = ["od.time", '>=', $param["startdate"]];
            $map[] = ["od.time", '<', $param["enddate"]];
        }

//        $users = InvitationModel::querytagUser($map, $findName);
        $users = InvitationModel::querytagUser1($map, $findName);

        //匹配助教信息
        $zhujiaos = db::table('xh_manager')->where(['del' => 0])->select();

        foreach ($users as $k => $v) {
            foreach ($zhujiaos as $k2 => $v2) {
                if ($v2['account'] == $v['zhujiao']) {
                    $users[$k]['zhujiaoname'] = $v2['nick'];
                }
            }
        }

        //拆分出各个助教的用户信息
        $senderunionid = [];
        foreach ($users as $k => $v) {
            if ($v['wx_unionid'] && $v['wx_unionid'] != '') {
                $senderunionid[$v['zhujiao']][] = $v['wx_unionid'];
            }

        }

//        if (isset($param["startdate"]) && !empty($param["startdate"]) && isset($param["enddate"]) && !empty($param["enddate"])) {
//            $map1[0] = $param["startdate"];
//            $map1[1] = $param["enddate"];
//        }

        $user2 = [];
        //分助教去查询具体的用户数据
        foreach ($senderunionid as $k => $v) {
            $a = self::getSenderUser($users, $k, $v);
            if ($user2) {
                // 使用 array_merge 函数合并数组
                $user2 = array_merge($user2, $a);
            } else {
                $user2 = $a;
            }

        }
        return Res::ok($user2);

    }
    /**
     * @author: oliver
     * @Description: 查询用户信息
     * @param {*} $param
     * @Date: 2024-06-28 00:11:50
     */
    public static function querytagUser_no($param) //oliver

    {

        //查询标签
        $map = [];
        $map1 = [];
        $users = [];
        $map["u.del"] = 0;
        $map[] = ["q.wx_unionid", '<>', ''];
        //权限管控
        $map = self::getAccountInfo($map, "u.zhujiao", $param["sender"]);

//        dump($param['tags1']);//包含的
        //        dump($param['tags']); //不包含的
        //        dump(array_diff($param['tags1'],$param['tags']));
        //        dump(array_diff($param['tags'],$param['tags1']));
        //        $in = array_diff($param['tags1'], $param['tags']);
        //        $not_in = array_diff($param['tags'], $param['tags1']);

//        if (isset($param["tags"]) && !empty($param["tags"])) {
        //            $map[] = ["u.tagid", 'not in', $param['tags']];
        //        }

//        $users1 = [];
        //        $users2 = [];
        //        $findName = "u.userid,u.zhujiao,q.wx_unionid,q.wx_name,q.wx_avatar,q.phone";
        //        if (isset($param['tags1']) && !empty($param['tags1'])) {
        //            $map1[] = ["u.tagid", 'in', $param['tags1']];
        //            $users1 = InvitationModel::querytagUser($map1, $findName);
        //        }
        //        if (isset($param['tags']) && !empty($param['tags'])) {
        //            $map[] = ["u.tagid", 'in', $param['tags']];
        //            $users2 = InvitationModel::querytagUser($map, $findName);
        //        }
        //        if(!empty($users1) && !empty($users2)  ){
        //            foreach($users1 as $k =>&$v){
        //                foreach($users2 as $kk=>&$vv){
        //                    if($v['userid'] == $vv['userid']){
        //                        unset($users1[$k]);
        //                        continue;
        //                    }
        //                }
        //            }
        //            $users = $users1;
        //        }else if(empty($users1) && !empty($users2)  ){
        //            $map[] = ["u.tagid", 'not in', $param['tags']];
        //            $users2 = InvitationModel::querytagUser($map, $findName);
        //            $users = $users2;
        //        } else if (!empty($users1) && empty($users2)) {
        //            $users = $users1;
        //        } else if (empty($users1) && empty($users2)) {
        //            $users = $users1;
        //        }
        if (isset($param["tags"]) && !empty($param["tags"])) {
            $map[] = ["u.tagid", 'in', $param['tags']];
        }

        $findName = "u.userid,u.zhujiao,q.wx_unionid,q.wx_name,q.wx_avatar,q.phone";

        if (isset($param["startdate"]) && !empty($param["startdate"]) && isset($param["enddate"]) && !empty($param["enddate"])) {
            $map[] = ["od.time", '>=', $param["startdate"]];
            $map[] = ["od.time", '<', $param["enddate"]];
        }

//        $users = InvitationModel::querytagUser($map, $findName);
        $users = InvitationModel::querytagUser1($map, $findName);

        //匹配助教信息
        $zhujiaos = db::table('xh_manager')->where(['del' => 0])->select();

        foreach ($users as $k => $v) {
            foreach ($zhujiaos as $k2 => $v2) {
                if ($v2['account'] == $v['zhujiao']) {
                    $users[$k]['zhujiaoname'] = $v2['nick'];
                }
            }
        }

        //拆分出各个助教的用户信息
        $senderunionid = [];
        foreach ($users as $k => $v) {
            if ($v['wx_unionid'] && $v['wx_unionid'] != '') {
                $senderunionid[$v['zhujiao']][] = $v['wx_unionid'];
            }

        }

//        if (isset($param["startdate"]) && !empty($param["startdate"]) && isset($param["enddate"]) && !empty($param["enddate"])) {
//            $map1[0] =  $param["startdate"];
//            $map1[1] =  $param["enddate"];
//        }

        $user2 = [];
        //分助教去查询具体的用户数据
        foreach ($senderunionid as $k => $v) {
            $a = self::getSenderUser($users, $k, $v);
            if ($user2) {
                // 使用 array_merge 函数合并数组
                $user2 = array_merge($user2, $a);
            } else {
                $user2 = $a;
            }

        }

        return Res::ok($user2);

    }

    /**
     * @author: zwx
     * @Description: 查询用户信息
     * @param {*} $param
     * @Date: 2024-06-28 00:11:50
     */
    public static function queryUser($param)
    {

        //查询标签
        $map = [];
        $map["u.del"] = 0;

        //权限管控
        $map = self::getAccountInfo($map, "u.zhujiao", $param["sender"]);

        if (isset($param["wx_name"]) && !empty($param["wx_name"])) {
            $map[] = ["u.wx_name", 'like', '%' . $param['wx_name'] . '%'];
        }

        if (isset($param["startdate"]) && !empty($param["startdate"]) && isset($param["enddate"]) && !empty($param["enddate"])) {
            $map[] = ["u.addtime", '>=', $param['startdate']];
            $map[] = ["u.addtime", '<', $param['enddate']];
        }

        $findName = "u.wx_userid as userid,u.zhujiao,u.wx_unionid,u.wx_name,u.wx_avatar,u.phone";

        $users = InvitationModel::queryUser($map, $findName);

        //匹配助教信息
        $zhujiaos = db::table('xh_manager')->where(['del' => 0])->select();

        foreach ($users as $k => $v) {
            foreach ($zhujiaos as $k2 => $v2) {
                if ($v2['account'] == $v['zhujiao']) {
                    $users[$k]['zhujiaoname'] = $v2['nick'];
                }
            }

        }

        //拆分出各个助教的用户信息
        $senderunionid = [];
        foreach ($users as $k => $v) {
            if ($v['zhujiao'] && $v['wx_unionid'] && $v['wx_unionid'] != '') {
                $senderunionid[$v['zhujiao']][] = $v['wx_unionid'];
            }
        }

        $user2 = [];
        //分助教去查询具体的用户数据
        foreach ($senderunionid as $k => $v) {
            $a = self::getSenderUser($users, $k, $v);
            if ($user2) {
                // 使用 array_merge 函数合并数组
                $user2 = array_merge($user2, $a);
            } else {
                $user2 = $a;
            }

        }

        return Res::ok($user2);

    }

    /**
     * @author: zwx
     * @Description: 单一规划师的客户数据
     * @param {*} $users
     * @param {*} $sender
     * @param {*} $unions
     * @Date: 2024-08-06 18:36:28
     */
    public static function getSenderUser($users, $sender, $unions)
    {

        $map2 = [];
        $map2[] = ["union_id", 'in', $unions];

        $map2["teacher_id"] = $sender;

        $ordercode = db::table('xh_order_code')->where($map2)->select()->toArray();

        $user2 = [];
        $unionid3 = [];
        foreach ($users as $k1 => $v1) {
            $a = true;
            foreach ($ordercode as $k => $v) {
                if ($v1['wx_unionid'] && $v1['wx_unionid'] != '' && $v['union_id'] == $v1['wx_unionid']) {
                    $user2[] = $v1;
                    $a = false;
                }
            }
            if ($a) {
                $unionid3[] = $v1['wx_unionid'];
            }
        }

        //根据订单上unionid过滤出剩余客户中自己的客户
        $map3 = [];
        $map3[] = ['o.wx_union_id', 'in', $unionid3];

        $map3['c.teacher_id'] = $sender;

//        if(count($mp) != 0){
//            $map3[] = ["o.time", '>=', $mp[0]];
//            $map3[] = ["o.time", '<', $mp[1]];
//        }
        $orders = db::table('xh_order_1')
            ->alias('o')
            ->join(['xh_order_code' => 'c'], 'c.order_id = o.id')
            ->where($map3)->group('c.teacher_id,o.wx_union_id')->select()->toArray();

        foreach ($users as $k1 => $v1) {
            foreach ($orders as $k => $v) {
                if ($v['wx_union_id'] == $v1['wx_unionid']) {
                    $user2[] = $v1;
                }
            }

        }
        return $user2;
    }

    /**
     * @author: zwx
     * @Description: 单一规划师的客户邀约数据
     * @param {*} $users
     * @param {*} $sender
     * @param {*} $unions
     * @Date: 2024-08-06 18:36:28
     */
    public static function getSenderInvitationUser($venue, $sender, $unions)
    {
        $where = [];
        $where[] = ['wx_unionid', 'in', $unions];
        $where['venue'] = $venue;
        $where['sender'] = $sender;
        $where['del'] = 0;
        $yiyaoyue = db::table('xh_siyu_invitation_user')->where($where)->field('wx_unionid,signin_status,sender')->group('sender,wx_unionid')->select()->toArray();

        return $yiyaoyue;
    }

    /**
     * @author: zwx
     * @Description: 单一规划师的客户邀约数据  不去重
     * @param {*} $users
     * @param {*} $sender
     * @param {*} $unions
     * @Date: 2024-08-06 18:36:28
     */
    public static function getSenderInvitationUser2($venue, $sender, $unions)
    {
        $where = [];
        $where[] = ['wx_unionid', 'in', $unions];
        $where['venue'] = $venue;
        $where['sender'] = $sender;
        $where['del'] = 0;
        $yiyaoyue = db::table('xh_siyu_invitation_user')->where($where)->field('wx_unionid,signin_status,sender,venue')->select()->toArray();

        return $yiyaoyue;
    }

    /**
     * @author: zwx
     * @Description: 查询用户信息  根据下单时间
     * @param {*} $param
     * @Date: 2024-06-28 00:11:50
     */
    public static function ordertime_queryUser($param)
    {

        //查询标签
        $map = [];
        $map["o.del"] = 0;
        $map["o.isfinished"] = 1;
        // $map["o.is_add_wx"] = 1;
        // $map[] = ["o.wx_union_id", '<>', ''];
        $map[] = ['o.pingtai', 'in', [1, 2, 4, 6]];
        //权限管控
        $map = self::getAccountInfo($map, "c.teacher_id", $param["sender"]);

        if (isset($param["startdate"]) && !empty($param["startdate"]) && isset($param["enddate"]) && !empty($param["enddate"])) {
            $map[] = ["o.time", '>=', $param['startdate']];
            $map[] = ["o.time", '<', $param['enddate']];
        }

        $map['q.del'] = 0;
        $map['m.del'] = 0;
        $findName = "DATE_FORMAT(o.time, '%Y-%m-%d') as date,q.wx_userid as userid,q.zhujiao,q.wx_unionid,q.wx_name,q.wx_avatar,q.phone,m.nick as zhujiaoname,o.id,o.is_add_wx";

        //1、查询出订单对应的unionid
        $user2 = Db::table('xh_order_1')
            ->alias('o')
            ->join(['xh_order_code' => 'c'], 'c.order_id = o.id')
            ->join(['xh_qwuser_1' => 'q'], 'q.wx_unionid = o.wx_union_id and q.zhujiao = c.teacher_id')
            ->join(['xh_manager' => 'm'], 'm.account = q.zhujiao', 'left')
            ->field($findName)
            ->where($map)
            ->order('o.time desc')
        // ->group('q.zhujiao,q.wx_unionid')
            ->select()->toArray();

        //拆分出各个助教的用户信息
        $senderunionid = []; //人员
        $senderunionid2 = []; //订单
        foreach ($user2 as $k => $v) {
            $senderunionid[$v['date']][$v['zhujiao']][] = $v['wx_unionid'];
            $senderunionid2[$v['date']][$v['zhujiao']][$v['wx_unionid']][] = $v['id'];
        }

        $yiyaoyue = [];
        $yi_yaoyue = []; //计数 邀约人数
        //分助教去查询具体的邀约用户数据
        foreach ($senderunionid as $k => $v) {
            foreach ($v as $k1 => $v1) {
                $c = array_unique($v1); //去重
                $a = self::getSenderInvitationUser($param['venue'], $k1, $c);
                $yi_yaoyue[$k][$k1] = $a;
                if ($yiyaoyue) {
                    // 使用 array_merge 函数合并数组
                    if ($a) {
                        $yiyaoyue = array_merge($yiyaoyue, $a);
                    }
                } else {
                    $yiyaoyue = $a;
                }

            }
        }

        //组合数据
        $list = [];
        foreach ($user2 as $k => $v) {
            //未邀约
            $list[$v['date']]['weiyaoyue']['id'] = $v['date'] . '_未邀约';
            $list[$v['date']]['weiyaoyue']['click'] = 0;
            $list[$v['date']]['weiyaoyue']['name'] = '未邀约';
            $list[$v['date']]['weiyaoyue']['date'] = $v['date'];

            if (!isset($list[$v['date']]['weiyaoyue']['num'])) {
                $list[$v['date']]['weiyaoyue']['num'] = 0;
                $list[$v['date']]['weiyaoyue']['ordersnum'] = 0;
                $list[$v['date']]['weiyaoyue']['orders'] = [];
                $list[$v['date']]['weiyaoyue']['user'] = [];
                $list[$v['date']]['weiyaoyue']['unionids'] = [];
                $list[$v['date']]['weiyaoyue']['weiyaoyue'] = [];
            }

            //邀约未到课
            $list[$v['date']]['weidaoke']['id'] = $v['date'] . '_未到课';
            $list[$v['date']]['weidaoke']['click'] = 0;
            $list[$v['date']]['weidaoke']['date'] = $v['date'];
            $list[$v['date']]['weidaoke']['name'] = '未到课';

            if (!isset($list[$v['date']]['weidaoke']['num'])) {
                $list[$v['date']]['weidaoke']['num'] = 0;
                $list[$v['date']]['weidaoke']['ordersnum'] = 0;
                $list[$v['date']]['weidaoke']['orders'] = [];
                $list[$v['date']]['weidaoke']['user'] = [];
                $list[$v['date']]['weidaoke']['unionids'] = [];
                $list[$v['date']]['weidaoke']['weidaoke'] = [];
            }

            //领课加V
            $list[$v['date']]['lingke_jiav']['id'] = $v['date'] . '_领课加V数';
            $list[$v['date']]['lingke_jiav']['click'] = 0;
            $list[$v['date']]['lingke_jiav']['date'] = $v['date'];
            $list[$v['date']]['lingke_jiav']['name'] = '领课加V数';

            if (!isset($list[$v['date']]['lingke_jiav']['num'])) {
                $list[$v['date']]['lingke_jiav']['num'] = 0;
                $list[$v['date']]['lingke_jiav']['ordersnum'] = 0;
                $list[$v['date']]['lingke_jiav']['orders'] = [];
                $list[$v['date']]['lingke_jiav']['user'] = [];
                $list[$v['date']]['lingke_jiav']['unionids'] = [];
                $list[$v['date']]['lingke_jiav']['lingke_jiav'] = [];
            }

            //已邀约
            $list[$v['date']]['yiyaoyue']['id'] = $v['date'] . '_已邀约';
            $list[$v['date']]['yiyaoyue']['click'] = 0;
            $list[$v['date']]['yiyaoyue']['date'] = $v['date'];
            $list[$v['date']]['yiyaoyue']['name'] = '已邀约';

            if (!isset($list[$v['date']]['yiyaoyue']['num'])) {
                $list[$v['date']]['yiyaoyue']['num'] = 0;
                $list[$v['date']]['yiyaoyue']['ordersnum'] = 0;
                $list[$v['date']]['yiyaoyue']['orders'] = [];
                $list[$v['date']]['yiyaoyue']['user'] = [];
                $list[$v['date']]['yiyaoyue']['unionids'] = [];
                $list[$v['date']]['yiyaoyue']['yiyaoyue'] = [];
            }

            //邀约已到课
            $list[$v['date']]['yiyaoyue_yidaoke']['id'] = $v['date'] . '_邀约已到课';
            $list[$v['date']]['yiyaoyue_yidaoke']['click'] = 0;
            $list[$v['date']]['yiyaoyue_yidaoke']['date'] = $v['date'];
            $list[$v['date']]['yiyaoyue_yidaoke']['name'] = '邀约已到课';

            if (!isset($list[$v['date']]['yiyaoyue_yidaoke']['num'])) {
                $list[$v['date']]['yiyaoyue_yidaoke']['num'] = 0;
                $list[$v['date']]['yiyaoyue_yidaoke']['ordersnum'] = 0;
                $list[$v['date']]['yiyaoyue_yidaoke']['orders'] = [];
                $list[$v['date']]['yiyaoyue_yidaoke']['user'] = [];
                $list[$v['date']]['yiyaoyue_yidaoke']['unionids'] = [];
                $list[$v['date']]['yiyaoyue_yidaoke']['yiyaoyue_yidaoke'] = [];
            }

            //领课加V计数
            if (count($list[$v['date']]['lingke_jiav']['orders']) == 0) {
                $list[$v['date']]['lingke_jiav']['orders'] = $senderunionid2[$v['date']][$v['zhujiao']][$v['wx_unionid']];
                $list[$v['date']]['lingke_jiav']['ordersnum'] = count($list[$v['date']]['lingke_jiav']['orders']);
            } else {
                $list[$v['date']]['lingke_jiav']['orders'] = array_merge($list[$v['date']]['lingke_jiav']['orders'], $senderunionid2[$v['date']][$v['zhujiao']][$v['wx_unionid']]);
                $list[$v['date']]['lingke_jiav']['ordersnum'] = count($list[$v['date']]['lingke_jiav']['orders']);
            }

            if ($v['is_add_wx'] == 1) {
                $list[$v['date']]['lingke_jiav']['user'][] = $v;
                $list[$v['date']]['lingke_jiav']['num']++;
                $list[$v['date']]['lingke_jiav']['unionids'][] = $v['wx_unionid'];
                $list[$v['date']]['lingke_jiav']['lingke_jiav'][] = ['zhujiao' => $v['zhujiao'], 'wx_unionid' => $v['wx_unionid']];
            }

            $a = true;
            foreach ($yiyaoyue as $k1 => $v1) {
                if ($v['wx_unionid'] == $v1['wx_unionid'] && $v['zhujiao'] == $v1['sender']) {
                    //已邀约计数
                    if (count($list[$v['date']]['yiyaoyue']['orders']) == 0) {
                        $list[$v['date']]['yiyaoyue']['orders'] = $senderunionid2[$v['date']][$v['zhujiao']][$v['wx_unionid']];
                        $list[$v['date']]['yiyaoyue']['ordersnum'] = count($list[$v['date']]['yiyaoyue']['orders']);
                    } else {
                        $list[$v['date']]['yiyaoyue']['orders'] = array_merge($list[$v['date']]['yiyaoyue']['orders'], $senderunionid2[$v['date']][$v['zhujiao']][$v['wx_unionid']]);
                        $list[$v['date']]['yiyaoyue']['ordersnum'] = count($list[$v['date']]['yiyaoyue']['orders']);
                    }
                    if ($v['is_add_wx'] == 1) {
                        $list[$v['date']]['yiyaoyue']['user'][] = $v;
                        $list[$v['date']]['yiyaoyue']['num']++;
                        $list[$v['date']]['yiyaoyue']['unionids'][] = $v['wx_unionid'];
                        $list[$v['date']]['yiyaoyue']['yiyaoyue'][] = ['zhujiao' => $v['zhujiao'], 'wx_unionid' => $v['wx_unionid']];
                    }

                    if ($v1['signin_status'] == 0) { //已邀约未到课计数
                        if (count($list[$v['date']]['weidaoke']['orders']) == 0) {
                            $list[$v['date']]['weidaoke']['orders'] = $senderunionid2[$v['date']][$v['zhujiao']][$v['wx_unionid']];
                            $list[$v['date']]['weidaoke']['ordersnum'] = count($list[$v['date']]['weidaoke']['orders']);
                        } else {
                            $list[$v['date']]['weidaoke']['orders'] = array_merge($list[$v['date']]['weidaoke']['orders'], $senderunionid2[$v['date']][$v['zhujiao']][$v['wx_unionid']]);
                            $list[$v['date']]['weidaoke']['ordersnum'] = count($list[$v['date']]['weidaoke']['orders']);
                        }
                        if ($v['is_add_wx'] == 1) {
                            $list[$v['date']]['weidaoke']['user'][] = $v;
                            $list[$v['date']]['weidaoke']['num']++;
                            $list[$v['date']]['weidaoke']['unionids'][] = $v['wx_unionid'];
                            $list[$v['date']]['weidaoke']['weidaoke'][] = ['zhujiao' => $v['zhujiao'], 'wx_unionid' => $v['wx_unionid']];
                        }
                    } else if ($v1['signin_status'] == 2) { //已邀约已到课计数
                        if (count($list[$v['date']]['yiyaoyue_yidaoke']['orders']) == 0) {
                            $list[$v['date']]['yiyaoyue_yidaoke']['orders'] = $senderunionid2[$v['date']][$v['zhujiao']][$v['wx_unionid']];
                            $list[$v['date']]['yiyaoyue_yidaoke']['ordersnum'] = count($list[$v['date']]['yiyaoyue_yidaoke']['orders']);
                        } else {
                            $list[$v['date']]['yiyaoyue_yidaoke']['orders'] = array_merge($list[$v['date']]['yiyaoyue_yidaoke']['orders'], $senderunionid2[$v['date']][$v['zhujiao']][$v['wx_unionid']]);
                            $list[$v['date']]['yiyaoyue_yidaoke']['ordersnum'] = count($list[$v['date']]['yiyaoyue_yidaoke']['orders']);
                        }
                        if ($v['is_add_wx'] == 1) {
                            $list[$v['date']]['yiyaoyue_yidaoke']['user'][] = $v;
                            $list[$v['date']]['yiyaoyue_yidaoke']['num']++;
                            $list[$v['date']]['yiyaoyue_yidaoke']['unionids'][] = $v['wx_unionid'];
                            $list[$v['date']]['yiyaoyue_yidaoke']['yiyaoyue_yidaoke'][] = ['zhujiao' => $v['zhujiao'], 'wx_unionid' => $v['wx_unionid']];
                        }
                    }
                    $a = false;
                }
            }
            //未邀约
            if ($a) {
                if (count($list[$v['date']]['weiyaoyue']['orders']) == 0) {
                    $list[$v['date']]['weiyaoyue']['orders'] = $senderunionid2[$v['date']][$v['zhujiao']][$v['wx_unionid']];
                    $list[$v['date']]['weiyaoyue']['ordersnum'] = count($list[$v['date']]['weiyaoyue']['orders']);
                } else {
                    $list[$v['date']]['weiyaoyue']['orders'] = array_merge($list[$v['date']]['weiyaoyue']['orders'], $senderunionid2[$v['date']][$v['zhujiao']][$v['wx_unionid']]);
                    $list[$v['date']]['weiyaoyue']['ordersnum'] = count($list[$v['date']]['weiyaoyue']['orders']);
                }
                if ($v['is_add_wx'] == 1) {
                    $list[$v['date']]['weiyaoyue']['user'][] = $v;
                    $list[$v['date']]['weiyaoyue']['num']++;
                    $list[$v['date']]['weiyaoyue']['unionids'][] = $v['wx_unionid'];
                    $list[$v['date']]['weiyaoyue']['weiyaoyue'][] = ['zhujiao' => $v['zhujiao'], 'wx_unionid' => $v['wx_unionid']];
                }
            }

        }

        // 按照date键对数组进行排序
        usort($user2, function ($a, $b) {
            return $b['date'] <=> $a['date'];
        });

        $data = [
            'list' => $list,
            'senderunionid' => $senderunionid,
            'senderunionid2' => $senderunionid2,
            'yi_yaoyue' => $yi_yaoyue,
        ];

        return Res::ok($data);

    }

    /**
     * @author: zwx
     * @Description: 根据权限，返回拼好的条件
     * @param {*} $map  条件数组
     * @param {*} $key  条件key
     * @param {*} $sender 登录人员账号
     * @Date: 2024-08-05 19:21:56
     */
    public static function getAccountInfo($map, $key, $sender)
    {

        $where = [];
        $where['m.account'] = $sender;
        $where['m.del'] = 0;
        //销售登录的用户信息
        $manager = db::table('xh_manager')
            ->alias('m')
            ->field('m.*,g.id as groupid,g.name as groupname,m.role_id')
            ->join(['xh_zhujiao_group' => 'g'], 'm.id=g.managerid', 'left')
            ->where($where)->find();
        // dump($manager);
        if (!$manager) {
            // dump(db::table('xh_manager')
            //     ->alias('m')
            //     ->field('m.*,g.id as groupid,g.name as groupname,m.role_id')
            //     ->join(['xh_zhujiao_group' => 'g'], 'm.id=g.managerid', 'left')
            //     ->where($where)->fetchSql()->findOrEmpty());
            $manager['senders'] = [$manager['account']];
            return;
        }

        if ($manager['role_id'] == 7) { //销售

            $manager['senders'] = [$manager['account']];

        } else if ($manager['role_id'] == 5) { //主管

            $senders = db::table('xh_manager')
                ->alias('m')
                ->field('l.userid')
                ->join(['xh_zhujiao_group' => 'g'], 'm.id=g.managerid', 'inner')
                ->join(['xh_zhujiao_group_list' => 'l'], 'l.groupid=g.id', 'inner')
                ->where(['m.account' => $sender, 'g.del' => 0, 'l.del' => 0])->select()->toArray();

            $manager['senders'] = array_column($senders, 'userid');

        } else { //admin

            $manager['senders'] = [];

        }

        //拼条件
        if ($manager['role_id'] == 7) { //销售权限  只能查自己的客户

            $map[$key] = $sender;

        } else if ($manager['role_id'] == 5) { //主管权限  可以查询自己所属的规划师的客户

            $map[] = [$key, 'in', $manager["senders"]];

        } else if ($manager['role_id'] == 1) { //超管权限  可以查询所有客户

        } else {
            return Res::error('权限不足，拒绝查询');
        }

        return $map;
    }

    /**
     * @author: zwx
     * @Description: 保存并发布  群发邀请计划
     * @param {*} $param
     * @Date: 2024-06-28 18:20:19
     */
    public static function savepublish($param)
    {

        $sender = $param['sender'];
        $liveId = $param['liveId'];
        $users = $param['senddata'];
        $textarea = $param['textarea'];

        //发送人信息
        $tutor = db::name('siyu_sys_member')->where(['user_name' => $sender])->find();

        //客户wx_userid
        $external_userid = array_column($users, 'userid');

        $time = date('Y-m-d H:i:s');

        //存储邀约计划
        $map = [];
        $map['liveId'] = $liveId;
        $map['venue'] = $param['venue'];
        $map['title'] = $param['title'];
        $map['time'] = $time;
        $map['count'] = count($users);
        $map['sender'] = $sender;
        $map['count_hav'] = 0;
        $map['result'] = '';

        $planid = InvitationModel::saveToPlan($map);

        //群发消息
        $title = '';
//        $url = env('Live.live_host') . '/?liveId=' . $liveId . '&tutorId=' . $tutor['uid'] . '&planId=' . $planid . '&';
        $url = env('Live.live_host') . '/?liveId=' . $liveId . '&tutorId=' . $tutor['uid'] . '&';
        $desc = str_replace('[链接]', $url, $textarea);

        $picture = '';

        //群发
        $result = self::sendQiyeMsg($sender, $external_userid, $title, $desc, $url, $picture);

        $result = json_decode($result, true);

        if ($result['errcode'] != 0) {
            return Res::error($result);
        }

        // $result['fail_list'] = [];

        //查询已发送人员ID
        $yifa = [];
        if ($result['fail_list']) {
            $yifa = array_diff($external_userid, $result['fail_list']);
        } else {
            $yifa = $external_userid;
        }

        $unions = [];
        foreach ($users as $k => $v) {
            if (in_array($v['userid'], $yifa)) {
                if (!empty($v['wx_unionid']) && $v['wx_unionid'] != '') {
                    $unions[] = $v['wx_unionid'];
                }
            }
        }

//        //存储邀约计划 (24-09-08  修改)
        //        $map = [];
        //        $map['liveId'] = $liveId;
        //        $map['venue'] = $param['venue'];
        //        $map['title'] = $param['title'];
        //        $map['time'] = $time;
        //        $map['count'] = count($users);
        //        $map['sender'] = $sender;
        //        $map['count_hav'] = count($yifa);
        //        $map['result'] = json_encode($result);
        //
        //        $planid = InvitationModel::saveToPlan($map);

        // 修改邀约计划
        Db::table('xh_siyu_invitation_plan')->where('id', $planid)->update(['count_hav' => count($yifa), 'result' => json_encode($result)]);

        //存储邀约计划   发送信息
        $map = [];
        $map['liveId'] = $liveId;
        $map['venue'] = $param['venue'];
        $map['title'] = $title;
        $map['desc'] = $desc;
        $map['msg'] = $textarea;
        $map['url'] = $url;
        $map['picture'] = $picture;
        $map['planid'] = $planid;
        $map['time'] = $time;

        $map['type'] = 1;

        $msgid = InvitationModel::saveToMsg($map);

        //存储邀约计划人员信息
        $map2 = [];
        foreach ($users as $k => $v) {
            foreach ($yifa as $k2 => $v2) {
                if ($v['userid'] == $v2) {
                    $map = [];
                    $map['liveId'] = $liveId;
                    $map['venue'] = $param['venue'];
                    $map['planid'] = $planid;
                    $map['msgid'] = $msgid;
                    $map['sender'] = $param['sender'];
                    $map['time'] = $time;
                    $map['invitation_status'] = 2;
                    $map['invitation_time'] = $time;

                    $map['external_userid'] = $v['userid'];
                    $map['wx_unionid'] = $v['wx_unionid'];

                    $map['nickname'] = $v['wx_name'];
                    $map['phone'] = $v['phone'];
                    $map['headimgurl'] = $v['wx_avatar'];

                    // foreach ($gy_orders as $k3 => $v3) {
                    //     if($v3['wx_union_id']==$v['wx_unionid']){
                    //         $map['order_1_id'] = $v3['id'];
                    //         $map['order_1_ordernum'] = $v3['order_num'];
                    //         $map['order_1_tel'] = $v3['tel'];
                    //     }
                    // }

                    $map2[] = $map;
                }
            }

        }
        $userid = InvitationModel::saveToUser($map2);

        //检查发送成功的人员，更新order1表
        $map = [];
        $map[] = ['wx_union_id', 'in', $unions];
        $map['del'] = 0;
        $map['pay_state'] = 1;
        $map[] = ['pingtai', 'in', [1, 2, 4, 6]];

        $data = [];
        $data['new_yaoyue_tag'] = 1;
        $data['new_yaoyue_tag_time'] = $time;
        InvitationModel::updateOrder1($map, $data);

        //回填数据live_user_detail
        $map = [];
        $map[] = ['wx_union_id', 'in', $unions];
        $map['del'] = 0;
        $map['pay_state'] = 1;
        $map[] = ['pingtai', 'in', [1, 2, 4, 6]];

        $orders = db::table('xh_order_1')->where($map)->select();

        foreach ($orders as $k => $v) {
            if (!empty($v['wx_union_id']) && $v['wx_union_id'] != '') {
                LiveManagerService::getLiveOrderState($liveId, $param['venue'], $v['id'], 1);
            }
        }

        $result['zongshu'] = count($users);
        $result['shibaishu'] = count($result['fail_list']);
        return Res::ok($result);

    }

    /**
     * @author: zwx
     * @Description: 企业消息群发
     * @param {*} $sender   发送者企业账号
     * @param {Array} $external_userid  客户external_userid数组
     * @param {*} $title  消息名称
     * @param {*} $desc   消息明细
     * @param {*} $url    链接
     * @param {*} $picture   图片
     * @Date: 2024-06-28 16:59:27
     */
    public static function sendQiyeMsg($sender, $external_userid, $title, $desc, $url2, $picture = '')
    {
        //测试服务器不要打开企业微信接口
        //测试服务器不要打开企业微信接口
        //测试服务器不要打开企业微信接口
        //测试服务器不要打开企业微信接口
        $token = getToken::getQiYeWeiXinAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_msg_template?access_token=" . $token;
        $post = [
            // "attachments" =>
            //     [
            //         // "msgtype" => "link",
            //         // "link" => [
            //         //     "title" => $title,
            //         //     "desc" => $desc,
            //         //     "picture" => $picture,
            //         //     "url" => $url2,
            //         // ]
            //         // "link" => [
            //         //     "title" => '邀请您参与 测试14点',
            //         //     "desc" => '直播时间：2024-06-19 14:00:00 至 2024-06-19 16:00:00
            //         //     您可点击下方链接，进入观看直播~',
            //         //     "picture" => "",
            //         //     "url" => env('Live.live_host').'/?liveId=75&tutorId=20',
            //         // ]
            //     ],
            "text" => ['content' => $desc],
            "sender" => $sender,
            "external_userid" => $external_userid,
        ];

        $res = getCurlRequest($url, "POST", $post);

        return json_encode($res);
    }

    /**
     * @author: zwx
     * @Description: 私域直播打标签
     * @Date: 2024-07-12 21:00:35
     */
    public function siyu_dabiaoqian()
    {
        //测试服务器不要打开企业微信接口
        //测试服务器不要打开企业微信接口
        //测试服务器不要打开企业微信接口
        //测试服务器不要打开企业微信接口
        while (true) {

            try {
                //获取直播id
                $ls = new LiveStatus(1);
                $liveId = $ls->get_dabiaoqian_live();

                if (!empty($liveId)) {
                    dump($liveId);
                    dump('取到了----' . $liveId[1]);
                    // self::_xiaoSiyuBiaoQian($liveId[1]);
                } else {
                    dump('sleep1');
                    sleep(1);
                    dump('sleep2');
                }
            } catch (\Throwable $th) {
                dump('报错了-----------------------------------------------------');
                dump($th);
            }

        }

    }

    public static function _xiaoSiyuBiaoQian($liveId)
    {
        try {
            //测试服务器不要打开企业微信接口
            //测试服务器不要打开企业微信接口
            //测试服务器不要打开企业微信接口
            //测试服务器不要打开企业微信接口
            $live = db::table('xh_siyu_live_manager')->where('id', $liveId)->find();
            if (!$live) {
                dump('直播已结束');
                return;
            }

            $venue = $live['venue'];
            if ($venue == 1) { //第一场   只打第一场到课标签
                $tags1 = ['etbU7dCQAAvAV3pcO48DXoyJlcpcAldg']; // 到课一号品第一天到课
                $map = [];
                $map['signin_status'] = 2;
                $map['liveId'] = $liveId;

                $daoke = db::table('xh_siyu_invitation_user')->where($map)->select();
                // dump(M('siyu_invitation_user')->_sql());
                foreach ($daoke as $k => $v) {
                    //打上短码标签
                    self::markTag($v['sender'], $v['external_userid'], $tags1, array());
                    dump($k . '--1--' . $v['sender'] . '------' . $v['external_userid']);
                    file_put_contents("./daokebiaoqian.txt", "daoke1:" . $liveId . '--1--' . $v['sender'] . '------' . $v['external_userid'] . date('Y-m-d H:i:s'));
                }
            } else if ($venue == 2) { //第二场   打第二场到课标签和成交标签
                $tags2 = ['etbU7dCQAAB3rSePbJjh2u8_Yq7EMu7Q']; // 到课一号品第二天到课
                $map = [];
                $map['signin_status'] = 2;
                $map['liveId'] = $liveId;
                $daoke = db::table('xh_siyu_invitation_user')->where($map)->select();
                // dump(M('siyu_invitation_user')->_sql());
                foreach ($daoke as $k => $v) {
                    //打上短码标签
                    self::markTag($v['sender'], $v['external_userid'], $tags2, array());
                    dump($k . '--2--' . $v['sender'] . '------' . $v['external_userid']);
                    file_put_contents("./daokebiaoqian.txt", "daoke2:" . $liveId . '--2--' . $v['sender'] . '------' . $v['external_userid'] . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
                }

                $tags = ['etbU7dCQAAO-P7KTr4thyYey-liYwocg']; //已成交一号品
                $map = [];
                $map['chengjiao_status'] = 2;
                $map['liveId'] = $liveId;
                $chengjiao = db::table('xh_siyu_invitation_user')->where($map)->select();
                // dump(M('siyu_invitation_user')->_sql());
                foreach ($chengjiao as $k => $v) {

                    //打上短码标签
                    // markTag($v['sender'], $v['external_userid'], array(), $tags);
                    self::markTag($v['sender'], $v['external_userid'], $tags, array());
                    dump($k . '--3--' . $v['sender'] . '------' . $v['external_userid']);
                    file_put_contents("./daokebiaoqian.txt", "chengjiao:" . $liveId . '--3--' . $v['sender'] . '------' . $v['external_userid'] . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
                }

            }

            return true;
        } catch (\Throwable $th) {
            dump('报错了-----------------------------------------------------');
            dump($th);
            file_put_contents("./daokebiaoqian.txt", "error:" . json_encode($th) . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
        }

    }

    /**
     * @author: zwx
     * @Description: 给客户打标签或者删除标签
     * * @param {*} $zhujiao   助教账号
     * @param {*} $external_userid   顾客userid
     * @param {array} $addtags    添加的标签数组
     * @param {array} $removetags 删除的标签数组
     * @Date: 2024-04-19 14:11:50
     */
    public static function markTag($zhujiao, $external_userid, $addtags, $removetags)
    {
        //测试服务器不要打开企业微信接口
        //测试服务器不要打开企业微信接口
        //测试服务器不要打开企业微信接口
        //测试服务器不要打开企业微信接口
        // 获取token
        $accessToken = getToken::getQiYeWeiXinAccessToken();
        $queryUrl = 'https://qyapi.weixin.qq.com/cgi-bin/externalcontact/mark_tag?access_token=' . $accessToken;

        $params = array();
        $params['userid'] = $zhujiao;
        $params['external_userid'] = $external_userid;

        if ($addtags) {
            $params['add_tag'] = $addtags;
        }
        if ($removetags) {
            $params['remove_tag'] = $removetags;
        }

        $result = getCurlRequest($queryUrl, "POST", $params);

        if ($result['errcode'] == 0) {
            if ($addtags) {
                self::addZhuJiaoTagid('add', $zhujiao, $external_userid, $addtags);
            }
            if ($removetags) {
                self::addZhuJiaoTagid('del', $zhujiao, $external_userid, $removetags);
            }

        } else {
            print_r($result);
            printf(date('Y-m-d H:i:s', time()) . '---打标签error----', "------userid-----" . $zhujiao . "------external_userid-----" . $external_userid . "------addtags-----" . json_encode($addtags) . "------removetags-----" . json_encode($removetags) . "------返回-----" . json_encode($result), false, 'siyu_dabiaoqian.txt');
        }

        return $result;

    }

    /**
     * 添加助教-标签
     */
    public static function addZhuJiaoTagid($type, $zhujiao, $userid, $tagids)
    {
        //测试服务器不要打开企业微信接口
        //测试服务器不要打开企业微信接口
        //测试服务器不要打开企业微信接口
        //测试服务器不要打开企业微信接口
        if ($type == 'add') {
            $data = array();
            foreach ($tagids as $k => $v) {
                $a = array();
                $a['tagid'] = $v;
                $a['zhujiao'] = $zhujiao;
                $a['userid'] = $userid;
                $a['time'] = date('Y-m-d H:i:s');
                $data[] = $a;
            }

            if ($data) {
                db::table('xh_qw_user_tags_1')->insertAll($data);
            }

        } else if ($type == 'del') {
            $data = array();
            $data[] = ['tagid', 'in', $tagids];
            // $data['tagid'] = array('in', $tagids);
            $data['zhujiao'] = $zhujiao;
            $data['userid'] = $userid;
            print_r($data);
            $tag = db::table('xh_qw_user_tags_1')->where($data)->select();
            if ($tag) {
                db::table('xh_qw_user_tags_1')->where($data)->save(['del' => 1]);
            }

        }

    }

    /**
     * @author: zwx
     * @Description: 获取邀约状态数据
     * @param {*} $param
     * @Date: 2024-08-08 18:31:22
     */
    public static function getStatusList($param)
    {

        // $data = [
        //     'date' => '',
        //     'venue1' => [
        //         'name' => '',
        //         'lingke_jiav' => [
        //             'num' => '',
        //             'user' => [
        //                 'wx_avatar' => '',
        //                 'wx_nickname' => '',
        //                 'zhujiao' => '',
        //                 'zhujiaoname' => '',
        //                 'wx_unionid' => '',
        //             ],
        //         ],
        //         'yiyaoyue' => '',
        //         'weiyaoyue' => '',
        //         'yaoyue_yidaoke' => '',
        //         'yaoyue_weidaoke1' => '',
        //         'yaoyue_weidaoke2' => '',
        //         'yaoyue_weidaoke3' => '',
        //         'yaoyue_weidaoke4' => '',
        //         'yaoyue_weidaoke5' => '',
        //         'yaoyue_weidaoke6' => '',
        //         'yaoyue_weidaoke7' => '',
        //         'yaoyue_weidaoke8' => '',
        //         'yaoyue_weidaoke9' => '',
        //         'yaoyue_weidaoke10' => ''
        //     ],
        //     'venue2' => [
        //         'name' => '',
        //         'lingke_jiav' => '',
        //         'yiyaoyue' => '',
        //         'weiyaoyue' => '',
        //         'yaoyue_yidaoke' => '',
        //         'yaoyue_weidaoke1' => '',
        //         'yaoyue_weidaoke2' => '',
        //         'yaoyue_weidaoke3' => '',
        //         'yaoyue_weidaoke4' => '',
        //         'yaoyue_weidaoke5' => '',
        //         'yaoyue_weidaoke6' => '',
        //         'yaoyue_weidaoke7' => '',
        //         'yaoyue_weidaoke8' => '',
        //         'yaoyue_weidaoke9' => '',
        //         'yaoyue_weidaoke10' => ''
        //     ],
        // ];

        $limit = !isset($param['pageSize']) ? 10 : (int) $param['pageSize'];
        $a = ($param['pageNumber'] - 1) * $limit;
        $offset = ($param['pageNumber']) * $limit;

        $total = 0;

        if (isset($param["pay_time"]) && !empty($param["pay_time"])) {

            $startDate = new DateTime($param["pay_time"][0]);
            $endDate = new DateTime($param["pay_time"][1]);

            //分页
            $ende = date('Y-m-d', strtotime($param["pay_time"][1]) + 86400); //明天
            $endDate = new DateTime($ende);
            $interval2 = $endDate->diff($startDate);
            $total = $interval2->days;

            $interval = new DateInterval('P1D'); // 每天
            $dateRange = new DatePeriod($startDate, $interval, $endDate);

            $changcis = [1, 2]; //场次

            foreach ($dateRange as $date) {
                // dump(date('Y-m-d', strtotime($startDate->getTimestamp())).'---'. date('Y-m-d', strtotime($date->format('Y-m-d')) + 86400));
                $data = [];
                $data['date'] = $date->format('Y-m-d');
                foreach ($changcis as $k => $v) {
                    $data['venue' . $v] = self::getJiaVNum(date('Y-m-d', strtotime($date->format('Y-m-d'))), date('Y-m-d', strtotime($date->format('Y-m-d')) + 86400), $v);
                }
                $list[] = $data;
            }

        } else {
            $Date = date('Y-m-d', time() + 86400); //明天
            $endDate = new DateTime($Date);
            $startDate = new DateTime('2024-06-28');
            //分页
            $interval2 = $endDate->diff($startDate);
            $total = $interval2->days;

            $changcis = [1, 2]; //场次

            $list = [];
            // 生成过去十天的日期
            for ($i = $a; $i < $offset; $i++) {
                $endDate = date('Y-m-d', strtotime("$Date -" . ($i) . " day"));
                $startDate = date('Y-m-d', strtotime("$Date -" . ($i + 1) . " day"));

                $data = [];
                $data['date'] = $startDate;
                foreach ($changcis as $k => $v) {
                    $data['venue' . $v] = self::getJiaVNum($startDate, $endDate, $v);
                }
                $list[] = $data;
            }
        }

        $datalist = [
            'list' => $list,
            'total' => $total,
        ];

        return Res::ok($datalist);
    }

    /**
     * @author: zwx
     * @Description: 根据日期计算出  领课加V数
     * @param {*} $s_date
     * @param {*} $e_date
     * @Date: 2024-08-08 18:58:02
     */
    public static function getJiaVNum($s_date, $e_date, $changci)
    {

        //查询领课加v数
        $map = [];
        $map["o.del"] = 0;
        $map["o.isfinished"] = 1;
        $map["o.is_add_wx"] = 1;
        // $map[] = ["o.wx_union_id", '<>', ''];
        $map['m.del'] = 0;
        $map[] = ['o.pingtai', 'in', [1, 2, 4, 6]];
        $map[] = ["o.time", '>=', $s_date];
        $map[] = ["o.time", '<', $e_date];

        $findName = "DATE_FORMAT(o.time, '%Y-%m-%d') as date,c.teacher_id,o.wx_union_id,m.nick as zhujiaoname";
        // //领课加V数
        // $user2 = Db::table('xh_order_1')
        //     ->alias('o')
        //     ->join(['xh_order_code' => 'c'], 'c.order_id = o.id')
        //     ->join(['xh_qwuser_1' => 'q'], 'q.wx_unionid = c.union_id and q.zhujiao = c.teacher_id')
        //     ->join(['xh_manager' => 'm'], 'm.account = q.zhujiao', 'left')
        //     ->field($findName)
        //     ->where($map)
        //     ->order('o.time desc')
        //     ->group('q.zhujiao,q.wx_unionid')
        //     ->select()->toArray();

        //领课加Vd订单数
        $user3 = Db::table('xh_order_1')
            ->alias('o')
            ->join(['xh_order_code' => 'c'], 'c.order_id = o.id')
            ->join(['xh_manager' => 'm'], 'm.account = c.teacher_id')
            ->field($findName)
            ->where($map)
            ->order('o.time desc')
        // ->group('c.teacher_id,o.wx_union_id')
            ->select()->toArray();

        //查询客户信息
        $unions = array_column($user3, 'wx_union_id');

        //去重  不空
        $unions2 = [];
        foreach ($unions as $k => $v) {
            if (!empty($v) && !in_array($v, $unions2)) {
                $unions2[] = $v;
            }
        }

        $findName2 = "q.wx_userid as userid,q.zhujiao,q.wx_unionid,q.wx_name,q.wx_avatar,q.phone";

        $map = [];
        $map['q.del'] = 0;
        $map[] = ['wx_unionid', 'in', $unions2];
        $qwuser = db::table('xh_qwuser_1')->alias('q')->where($map)->field($findName2)->group('q.zhujiao,q.wx_unionid')->select()->toArray();

        // //查询邀约信息
        // $yiyaoyue= [];
        // $where = [];
        // $where[] = ['wx_unionid', 'in', $unions];
        // $where['venue'] = $changci;
        // // $where['sender'] = $sender;
        // $where['del'] = 0;
        // $yiyaoyue2 = db::table('xh_siyu_invitation_user')->where($where)->field('wx_unionid,signin_status,sender')->select()->toArray();

        //重组为以助教为key的二维数组
        $senderunionid = [];
        $user2 = [];
        $user3_quchong = [];
        foreach ($user3 as $k1 => $v1) {
            foreach ($qwuser as $k2 => $v2) {
                if ($v1['teacher_id'] == $v2['zhujiao'] && $v1['wx_union_id'] == $v2['wx_unionid']) {

                    if (!in_array($v1['teacher_id'] . '@' . $v1['wx_union_id'], $user3_quchong)) {
                        $user3_quchong[] = $v1['teacher_id'] . '@' . $v1['wx_union_id'];

                        $a['date'] = $v1['date'];
                        $a['zhujiaoname'] = $v1['zhujiaoname'];
                        $a['userid'] = $v2['userid'];
                        $a['zhujiao'] = $v2['zhujiao'];
                        $a['wx_unionid'] = $v2['wx_unionid'];
                        $a['wx_name'] = $v2['wx_name'];
                        $a['wx_avatar'] = $v2['wx_avatar'];
                        $a['phone'] = $v2['phone'];
                        $user2[] = $a;
                        $senderunionid[$v1['date']][$v1['teacher_id']][] = $v1['wx_union_id'];
                    }
                    $user3[$k1]['userid'] = $v2['userid'];
                    $user3[$k1]['zhujiao'] = $v2['zhujiao'];
                    $user3[$k1]['wx_unionid'] = $v2['wx_unionid'];
                    $user3[$k1]['wx_name'] = $v2['wx_name'];
                    $user3[$k1]['wx_avatar'] = $v2['wx_avatar'];
                    $user3[$k1]['phone'] = $v2['phone'];
                }

            }

            // foreach ($yiyaoyue2 as $k3 => $v3) {
            //     if($v3['sender']==$v1['teacher_id'] && $v3['wx_unionid']==$v1['wx_union_id']){
            //         $yiyaoyue[] = $v3;
            //     }
            // }
        }

        //根据助教分组查询对应的邀请记录
        $yiyaoyue = [];
        //分助教去查询具体的邀约用户数据
        foreach ($senderunionid as $k => $v) {
            foreach ($v as $k1 => $v1) {
                $a = self::getSenderInvitationUser2($changci, $k1, $v1);
                if ($yiyaoyue) {
                    // 使用 array_merge 函数合并数组
                    if ($a) {
                        $yiyaoyue = array_merge($yiyaoyue, $a);
                    }
                } else {
                    $yiyaoyue = $a;
                }
            }
        }

        //组合计算数据
        $lingke_jiav_user = []; //领课加V 数

        $yiyaoyue_quchong = []; //去重后的已邀约数
        $yiyaoyue_quchong_user = []; //去重后的已邀约人信息

        $weiyaoyue_user = []; //未邀约人信息

        $yidaoke_quchong = []; //去重后的已到课人信息
        $yidaoke_quchong_user = []; //去重后的已到课人信息

        $yaoyue_weidaoke = []; //邀约未到课次数
        $yaoyue_weidaoke_user = []; //邀约未到课人员信息

        if ($user2 && $yiyaoyue) {
            foreach ($user2 as $k => $v) {
                $lingke_jiav_user[] = $v;
                $a = true;
                foreach ($yiyaoyue as $k1 => $v1) {
                    if ($v['zhujiao'] == $v1['sender'] && $v['wx_unionid'] == $v1['wx_unionid']) {
                        //已邀约数 去重
                        if (!in_array($v1['sender'] . '@' . $v1['wx_unionid'], $yiyaoyue_quchong)) {
                            $yiyaoyue_quchong[] = $v1['sender'] . '@' . $v1['wx_unionid'];
                            $yiyaoyue_quchong_user[] = $v;
                            $a = false;
                        }

                        //已邀约已到课数 去重
                        if (!in_array($v1['sender'] . '@' . $v1['wx_unionid'], $yidaoke_quchong) && $v1['signin_status'] == 2) {
                            $yidaoke_quchong[] = $v1['sender'] . '@' . $v1['wx_unionid'];
                            $yidaoke_quchong_user[] = $v;
                        }

                        //邀约未到课数  不去重
                        if ($v1['signin_status'] == 0) {
                            isset($yaoyue_weidaoke[$v1['sender'] . '@' . $v1['wx_unionid']]['num']) ? $yaoyue_weidaoke[$v1['sender'] . '@' . $v1['wx_unionid']]['num']++ : $yaoyue_weidaoke[$v1['sender'] . '@' . $v1['wx_unionid']]['num'] = 1;
                            $yaoyue_weidaoke_user[$v1['sender'] . '@' . $v1['wx_unionid']]['user'] = $v;
                        }

                    }
                }
                //未邀约数
                if ($a) {
                    $weiyaoyue_user[] = $v;
                }
            }
        }

        //组合数据
        $venue = [];
        $venue['name'] = $changci == 1 ? '第一场' : '第二场';
        $venue['lingke_jiav_order'] = ['num' => count($user3), 'user' => $user3]; //领课加V单数
        $venue['lingke_jiav'] = ['num' => count($lingke_jiav_user), 'user' => $lingke_jiav_user]; //领课加V人数
        $venue['weiyaoyue'] = ['num' => count($weiyaoyue_user), 'user' => $weiyaoyue_user]; //未邀约
        $venue['yiyaoyue'] = ['num' => count($yiyaoyue_quchong), 'user' => $yiyaoyue_quchong_user]; //已邀约
        $venue['yaoyue_yidaoke'] = ['num' => count($yidaoke_quchong), 'user' => $yidaoke_quchong_user]; //邀约已到课

        //邀约未到课1-10次
        $venue['yaoyue_weidaoke1']['num'] = 0;
        $venue['yaoyue_weidaoke1']['user'] = [];

        $venue['yaoyue_weidaoke2']['num'] = 0;
        $venue['yaoyue_weidaoke2']['user'] = [];

        $venue['yaoyue_weidaoke3']['num'] = 0;
        $venue['yaoyue_weidaoke3']['user'] = [];

        $venue['yaoyue_weidaoke4']['num'] = 0;
        $venue['yaoyue_weidaoke4']['user'] = [];

        $venue['yaoyue_weidaoke5']['num'] = 0;
        $venue['yaoyue_weidaoke5']['user'] = [];

        $venue['yaoyue_weidaoke6']['num'] = 0;
        $venue['yaoyue_weidaoke6']['user'] = [];

        $venue['yaoyue_weidaoke7']['num'] = 0;
        $venue['yaoyue_weidaoke7']['user'] = [];

        $venue['yaoyue_weidaoke8']['num'] = 0;
        $venue['yaoyue_weidaoke8']['user'] = [];

        $venue['yaoyue_weidaoke9']['num'] = 0;
        $venue['yaoyue_weidaoke9']['user'] = [];

        $venue['yaoyue_weidaoke10']['num'] = 0;
        $venue['yaoyue_weidaoke10']['user'] = [];

        if ($user2 && $yiyaoyue) {
            foreach ($yaoyue_weidaoke as $k => $v) {

                switch ($v['num']) {
                    case 1:

                        $venue['yaoyue_weidaoke1']['user'][] = $yaoyue_weidaoke_user[$k]['user'];
                        $venue['yaoyue_weidaoke1']['num'] = count($venue['yaoyue_weidaoke1']['user']);
                        break;
                    case 2:

                        $venue['yaoyue_weidaoke2']['user'][] = $yaoyue_weidaoke_user[$k]['user'];
                        $venue['yaoyue_weidaoke2']['num'] = count($venue['yaoyue_weidaoke2']['user']);
                        break;
                    case 3:
                        $venue['yaoyue_weidaoke3']['user'][] = $yaoyue_weidaoke_user[$k]['user'];
                        $venue['yaoyue_weidaoke3']['num'] = count($venue['yaoyue_weidaoke3']['user']);
                        break;
                    case 4:
                        $venue['yaoyue_weidaoke4']['user'][] = $yaoyue_weidaoke_user[$k]['user'];
                        $venue['yaoyue_weidaoke4']['num'] = count($venue['yaoyue_weidaoke4']['user']);
                        break;
                    case 5:
                        $venue['yaoyue_weidaoke5']['user'][] = $yaoyue_weidaoke_user[$k]['user'];
                        $venue['yaoyue_weidaoke5']['num'] = count($venue['yaoyue_weidaoke5']['user']);
                        break;
                    case 6:
                        $venue['yaoyue_weidaoke6']['user'][] = $yaoyue_weidaoke_user[$k]['user'];
                        $venue['yaoyue_weidaoke6']['num'] = count($venue['yaoyue_weidaoke6']['user']);
                        break;
                    case 7:
                        $venue['yaoyue_weidaoke7']['user'][] = $yaoyue_weidaoke_user[$k]['user'];
                        $venue['yaoyue_weidaoke7']['num'] = count($venue['yaoyue_weidaoke7']['user']);
                        break;
                    case 8:
                        $venue['yaoyue_weidaoke8']['user'][] = $yaoyue_weidaoke_user[$k]['user'];
                        $venue['yaoyue_weidaoke8']['num'] = count($venue['yaoyue_weidaoke8']['user']);
                        break;
                    case 9:
                        $venue['yaoyue_weidaoke9']['user'][] = $yaoyue_weidaoke_user[$k]['user'];
                        $venue['yaoyue_weidaoke9']['num'] = count($venue['yaoyue_weidaoke9']['user']);
                        break;
                    case 10:
                        $venue['yaoyue_weidaoke10']['user'][] = $yaoyue_weidaoke_user[$k]['user'];
                        $venue['yaoyue_weidaoke10']['num'] = count($venue['yaoyue_weidaoke10']['user']);
                        break;

                    default:
                        # code...
                        break;
                }

            }
        }

        $venue['yiyaoyue0'] = $yiyaoyue;
        $venue['yaoyue_weidaoke0'] = $yaoyue_weidaoke;
        return $venue;

    }

    /**
     * 删除邀约计划
     * @param $param
     * @author cc
     */
    public static function deletePlan($param)
    {
        if (!isset($param['id']) || empty($param['id'])) {
            return Res::error('id不能为空');
        }
        if (!isset($param['sender']) || empty($param['sender'])) {
            return Res::error('创建人不能为空');
        }
        $userIdArr = db::name('zhujiao_group_list')->where(['del' => 0, 'group_leader' => $param['user_name']])->column('userid');
        if ($param['role_id'] == 12 && !in_array($userIdArr, $param['sender'])) {
            return Res::error('暂无权限');
        }
        $planInfo = Db::table('xh_siyu_invitation_plan')->where('id', $param['id'])->find();
        if (!$planInfo) {
            return Res::error('邀约计划不存在');
        }
        if ($param['role_id'] == 11 && $planInfo['sender'] != $param['user_name']) {
            return Res::error('不是本人创建，无法删除');
        }
        Db::startTrans();
        try {
            Db::table('xh_siyu_invitation_plan')->where('id', $planInfo['id'])->update(['del' => 1]);
            Db::table('xh_siyu_invitation_user')->where('planid', $planInfo['id'])->update(['del' => 1]);

            Db::commit();
            return Res::ok('删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            return Res::error('删除失败');
        }
    }

    /**
     * @author: zwx
     * @Description: 公域订单邀约统计
     * @param {*} $param
     * @Date: 2024-09-19 11:58:22
     */
    public static function getOrderList($param)
    {

        $liveId = $param['liveId']; //直播ID

        if (!$liveId) {
            return Res::error('直播ID不能为空');
        }

        //查询直播信息
        $liveinfo = db::table('xh_siyu_live_manager')->where(['id' => $liveId])->find();

        if ($liveinfo['venue'] == 1) {
            $liveinfo['changci'] = "第一场";
        } else if ($liveinfo['venue'] == 2) {
            $liveinfo['changci'] = "第一场";
        } else {
            $liveinfo['changci'] = "";
        }

        //统计邀约到课成交数据
        $sql = "SELECT
                    a.date,
                    a.yaoyue_num,
                    a.daoke_num,
                    CONCAT( FORMAT( a.daoke_num / a.yaoyue_num * 100, 2 ), '%' ) AS yaoyuedaoke_lv,
                    a.chengjiao_num,
                    CONCAT( FORMAT( a.chengjiao_num / a.yaoyue_num * 100, 2 ), '%' ) AS yaoyuechengjiao_lv,
                    IFNULL( CONCAT( FORMAT( a.chengjiao_num / a.daoke_num * 100, 2 ), '%' ), 0 ) AS daokechengjiao_lv
                FROM
                    (
                    SELECT
                        DATE_FORMAT( o.time, '%Y-%m-%d' ) AS date,
                        sum( CASE WHEN u.invitation_status = 2 THEN 1 ELSE 0 END ) AS yaoyue_num,
                        sum( CASE WHEN u.signin_status = 2 THEN 1 ELSE 0 END ) AS daoke_num,
                        sum( CASE WHEN u.chengjiao_status = 2 THEN 1 ELSE 0 END ) AS chengjiao_num
                    FROM
                        xh_order_1 o
                        INNER JOIN xh_siyu_invitation_user u ON o.wx_union_id = u.wx_unionid
                    WHERE
                        u.liveId = '" . $liveId . "'
                        AND u.del = 0
                        AND u.wx_unionid <> 'ogn1qwy0fFIxdGOouHgBDKw5AhPw'
                        AND u.wx_unionid <> 'ogn1qwzdpxsDpLhmAF7Fbf9mtEPA'
                        AND o.wx_union_id <> 'ogn1qwy0fFIxdGOouHgBDKw5AhPw'
                        AND o.wx_union_id <> 'ogn1qwzdpxsDpLhmAF7Fbf9mtEPA'
                        AND u.wx_unionid IS NOT NULL
                        AND o.wx_union_id IS NOT NULL
                        AND o.del = 0
                    GROUP BY
                        date
                    ORDER BY
                        date DESC
                    ) a;";

        $data = Db::query($sql);

        $datalist = [
            'list' => $data,
            'liveinfo' => $liveinfo,
        ];

        return Res::ok($datalist);

    }

    /**
     * 获取直播订阅用户
     * @param $param
     * @author succ
     */
    public static function getUserList($id)
    {

        $map = [];
        $map['del'] = 0; // 确保未删除
        $map['voice_tel'] = 0; // 未发送
        $map['liveId'] = $id; // 使用直播间 ID 进行过滤

        // 查询 wx_unionid 和手机号，并进行去重
        $chengjiao = Db::table('xh_siyu_invitation_user')
            ->field('wx_unionid,liveId') // 查询 wx_unionid 和手机号
            ->where($map)
            ->group('wx_unionid') // 根据 wx_unionid分组
            ->select();
        return $chengjiao ? $chengjiao->toArray() : [];
    }

    public static function markTagWithLiveIdAndUserId($liveId, $userId)
    {
        $live = db::table('xh_siyu_live_manager')->where('id', $liveId)->find();
        if (!$live) {
            if ($live->status == 2) {
                dump('直播已结束');
                return;
            }
        }

        $userInfo = db::table('xh_siyu_user')->where('id', $userId)->find();
        if (!$userInfo) {
            dump('用户不存在');
            return;
        }

        $venue = $live['venue'];
        $tags = [];
        if ($venue == 1) { //第一场   只打第一场到课标签
            $tags = ['etr4A1UwAAF37Niy8CMufOXG9UvszMFg']; // 到课一号品第一天到课
        } else if ($venue == 2) { //第二场   打第二场到课标签和成交标签
            $tags = ['etr4A1UwAAIT12cy0tdhwG6VWy6ePxKA']; // 到课一号品第二天到课
        }

        $map = [];
        $map['signin_status'] = 2;
        $map['liveId'] = $liveId;
        $map['wx_unionid'] = $userInfo['unionid'];
        $daoke = db::table('xh_siyu_invitation_user')->where($map)->select();
        // dump(M('siyu_invitation_user')->_sql());
        foreach ($daoke as $k => $v) {
            //打上短码标签
            self::markTag($v['sender'], $v['external_userid'], $tags, array());
            dump($k . '--2--' . $v['sender'] . '------' . $v['external_userid']);
        }

        return true;
    }

}
